use std::io::BufRead;

pub fn converter(input: &str, tp: &str) -> String {
    let ph_dict = match tp {
        "s2t" => "STPhrases.txt",
        "t2s" => "TSPhrases.txt",
        _ => {
            return input.to_string();
        }
    };
    let f = std::fs::OpenOptions::new()
        .read(true)
        .open(ph_dict)
        .unwrap();
    let reader = std::io::BufReader::new(f);
    let mut _lastf = "".to_string();
    let mut _lastt = "".to_string();
    for line in reader.lines() {
        let line = line.unwrap();
        let mut parts = line.split("	");
        let _from = parts.next().unwrap();
        let _from = _from
            .chars()
            .enumerate()
            .map(|(i, c)| {
                if c == '.' {
                    return _lastf.chars().nth(i).unwrap();
                }
                return c;
            })
            .collect::<String>();
        _lastf = _from.to_string();
        let _to = parts.next().unwrap();
        let _to = _to
            .chars()
            .enumerate()
            .map(|(i, c)| {
                if c == '.' {
                    return _lastt.chars().nth(i).unwrap();
                }
                if c == '+' {
                    return _from.chars().nth(i).unwrap();
                }
                return c;
            })
            .collect::<String>();
        _lastt = _to.to_string();
        if _from == input {
            return _to.to_string();
        }
    }

    let ch_dict = match tp {
        "s2t" => "STCharacters.txt",
        "t2s" => "TSCharacters.txt",
        _ => {
            return input.to_string();
        }
    };
    let f = std::fs::OpenOptions::new()
        .read(true)
        .open(ch_dict)
        .unwrap();
    let reader = std::io::BufReader::new(f);
    let mut input = input.to_string();
    for line in reader.lines() {
        let line = line.unwrap();
        let mut parts = line.split("	");
        let _from = parts.next().unwrap();
        let _to = parts.next().unwrap();

        // _from -> _to
        input = input.replace(_from, _to);
    }

    input
}
